package com.naodong.shenluntiku.mvp.view.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewStub;
import android.view.animation.Interpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Scroller;

import com.naodong.shenluntiku.R;
import com.naodong.shenluntiku.di.component.DaggerAssessmentComponent;
import com.naodong.shenluntiku.di.module.AssessmentModule;
import com.naodong.shenluntiku.di.module.CollectOperateModule;
import com.naodong.shenluntiku.mvp.contract.AssessmentContract;
import com.naodong.shenluntiku.mvp.contract.CollectOperateContract;
import com.naodong.shenluntiku.mvp.model.bean.Assessment;
import com.naodong.shenluntiku.mvp.model.bean.CollectType;
import com.naodong.shenluntiku.mvp.model.bean.EventBusTag;
import com.naodong.shenluntiku.mvp.model.bean.OnceTipType;
import com.naodong.shenluntiku.mvp.model.bean.SubjectInfo;
import com.naodong.shenluntiku.mvp.model.data.manager.BoxManager;
import com.naodong.shenluntiku.mvp.presenter.AssessmentPresenter;
import com.naodong.shenluntiku.mvp.presenter.CollectOperatePresenter;
import com.naodong.shenluntiku.mvp.view.adapter.AssessmentFragmentAdapter;
import com.naodong.shenluntiku.mvp.view.widget.TopTipViewManager;
import com.naodong.shenluntiku.util.AppUtil;
import com.squareup.phrase.Phrase;
import com.yatatsu.autobundle.AutoBundleField;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;

import javax.inject.Inject;

import butterknife.BindView;
import me.shingohu.man.base.BaseMVPActivity;
import me.shingohu.man.di.component.AppComponent;
import me.shingohu.man.intergation.EventManager;
import me.shingohu.man.model.bean.SimpleEvent;


/**
 * 通过Template生成对应页面的MVP和Dagger代码,请注意输入框中输入的名字必须相同
 * 由于每个项目包结构都不一定相同,所以每生成一个文件需要自己导入import包名,可以在设置中设置自动导入包名
 * 请在对应包下按以下顺序生成对应代码,Contract->Model->Presenter->Activity->Module->Component
 * 因为生成Activity时,Module和Component还没生成,但是Activity中有它们的引用,所以会报错,但是不用理会
 * 继续将Module和Component生成完后,编译一下项目再回到Activity,按提示修改一个方法名即可
 * 如果想生成Fragment的相关文件,则将上面构建顺序中的Activity换为Fragment,并将Component中inject方法的参数改为此Fragment
 */

/**
 * Created by hujie on 17/5/10.
 */

public class AssessmentActivity extends BaseMVPActivity<AssessmentPresenter> implements AssessmentContract.View, CollectOperateContract.View {

    public static final int FROM_STUDY = 2;
    public static final int FROM_FIND = 1;


    @BindView(R.id.viewPager)
    ViewPager viewPager;

    @AutoBundleField
    String title;
    @AutoBundleField
    int id;
    @AutoBundleField
    int from;//来源 学习 和发现

    @AutoBundleField(required = false)
    String tip;

    AssessmentFragmentAdapter mAdapter;
    ViewPager.SimpleOnPageChangeListener pageChangeListener;

    @BindView(R.id.menuView)
    LinearLayout menuView;
    ImageView collectView;


    @BindView(R.id.contentView)
    LinearLayout contentView;

    @Inject
    CollectOperatePresenter collectPresenter;

    TopTipViewManager topTipViewManager;

    private int lastPagerMode = 1; //最后一页显示什么  答题卡(1) 还是 结果(3),还是继续做题(5)

    @Override
    public void setupActivityComponent(AppComponent appComponent) {

        DaggerAssessmentComponent
                .builder()
                .appComponent(appComponent)
                .collectOperateModule(new CollectOperateModule(this))
                .assessmentModule(new AssessmentModule(this))//请将AssessmentModule()第一个首字母改为小写
                .build()
                .inject(this);


    }


    private void addRightCollectView() {
        collectView = (ImageView) LayoutInflater.from(this).inflate(R.layout.menu_image, null);
        menuView.addView(collectView);
        collectView.setBackgroundResource(R.drawable.collect_selector);
        menuView.setOnClickListener(v -> {
            SubjectInfo subjectInfo = mPresenter.getAssessment().getSubjects().get(viewPager.getCurrentItem());
            collectPresenter.requestPostCollect(subjectInfo.getuSubId(), CollectType.SUBJECTTYPE_ID, BoxManager.getInstance().queryBoxCollectStatusByIdAndType(subjectInfo.getuSubId(), 1));
        });
    }

    @Override
    protected void onCreateInit(Bundle savedInstanceState) {

        mToolbar.setNavigationIcon(R.drawable.vector_drawable_ico_clear);
        addRightCollectView();//添加收藏按钮
        setViewPager();
        mPresenter.getAssessment(from, id);
        setTitle(title);


    }

    private void setViewPager() {
        pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                if (mPresenter.getAssessment().getAssessNum() == position) {
                    if (lastPagerMode == 1) {
                        setTitle("答题卡");
                    } else if (lastPagerMode == 3) {
                        setTitle("作答结果");
                    } else if (lastPagerMode == 5) {
                        setTitle("继续做题");
                    }
                    menuView.setVisibility(View.INVISIBLE);
                } else {
                    if (lastPagerMode == 3) {
                        lastPagerMode = 5;
                    }
                    mAdapter.updateLastPagerMode(lastPagerMode);
                    menuView.setVisibility(View.VISIBLE);
                    refreshMenuView();
                    setCurrentIndexTitle(position + 1, mPresenter.getAssessment().getAssessNum());
                }
            }
        };
        setSliderTransformDuration(viewPager, 600);
        viewPager.addOnPageChangeListener(pageChangeListener);
    }


    private void refreshMenuView() {
        int id = mPresenter.getAssessment().getSubjects().get(viewPager.getCurrentItem()).getuSubId();
        menuView.setSelected(BoxManager.getInstance().queryBoxCollectStatusByIdAndType(id, 1));
    }


    @Override
    protected boolean userEventBus() {
        return true;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SimpleEvent event) {
        if (event.getType() == EventBusTag.TO_NEXT_SUBJECT) {
            if (viewPager.getCurrentItem() != viewPager.getChildCount()) {
                viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
            }
        }
        if (event.getType() == EventBusTag.TO_ASSIGN_SUBJECT) {
            viewPager.setCurrentItem(event.getIntEvent(), false);
        }
        if (event.getType() == EventBusTag.SUBMIT_ASSESSMENT) {
            mPresenter.submitAssessment();
        }
        if (event.getType() == EventBusTag.CHECK_ASSESSMENT_RESULT) {
            viewPager.setCurrentItem(0, false);
        }
        if (event.getType() == EventBusTag.GO_ON_ASSESSMENT) {
            startActivity(AssessmentActivityAutoBundle.builder(title, id, from).build(mActivity));
            finish();
        }
    }


    @Override
    protected boolean userAutoBindBundle() {
        return true;
    }

    @Override
    protected int layoutId() {
        return R.layout.a_assessment;
    }

    @Override
    public void showMessage(String msg) {

    }

    @Override
    protected void gc() {
        if (topTipViewManager != null) {
            topTipViewManager.destory();
        }
        super.gc();
    }

    @Override
    public void onRequesrStart() {
        progressHudUtil.showProgressHud(false);
    }

    @Override
    public void onRequestFinish() {
        progressHudUtil.dismissProgressHud();
    }


    @Override
    public void setAssessment(Assessment assessment) {

        if (!TextUtils.isEmpty(tip)) {
            if (topTipViewManager == null) {
                topTipViewManager = new TopTipViewManager(contentView);
            }
            topTipViewManager.showTipView(tip);
            tip = null;
        }

        checkNeedShowTip();
        setCurrentIndexTitle(1, assessment.getAssessNum());
        setData(assessment);
        viewPager.setCurrentItem(0);
        refreshMenuView();
    }


    private void checkNeedShowTip() {
        if (!BoxManager.getInstance().queryBoxOnceStatusByType(OnceTipType.assessment_scroller_tip)) {
            BoxManager.getInstance().putBoxOnce(OnceTipType.assessment_scroller_tip, true);
            AppUtil.startOnceTipActivity(this, OnceTipType.assessment_scroller_tip, null);
        }
    }


    private void setData(Assessment assessment) {
        menuView.setVisibility(View.VISIBLE);
        mAdapter = new AssessmentFragmentAdapter(getSupportFragmentManager(), assessment, lastPagerMode);
        viewPager.setAdapter(mAdapter);
    }

    @Override
    public void onSubmitAssessmentSuccess(Assessment assessment) {
        lastPagerMode = 3;
        setData(assessment);
        viewPager.setCurrentItem(mAdapter.getCount());
        if (from == FROM_FIND) {
            EventManager.getInstance().postEvent(EventBusTag.NOTIFY_FINDFRAGMENT_REFRESH);
        } else if (from == FROM_STUDY) {
            EventManager.getInstance().postEvent(EventBusTag.NOTIFY_FINDFRAGMENT_REFRESH);
            EventManager.getInstance().postIntEvent(EventBusTag.NOTIFY_STUDYFRAGMENT_UPDATE_DATA, id);
        }
    }


    @Override
    public void showEmptyView() {
        ViewStub stub = (ViewStub) findViewById(R.id.errorViewStub);
        View view = stub.inflate();
        view.setVisibility(View.VISIBLE);
        ImageView iv = (ImageView) view.findViewById(R.id.errorImage);
        iv.setImageResource(R.drawable.img_good_tag);
        view.findViewById(R.id.ctbBtn).setOnClickListener(v -> {
            Intent intent = new Intent(this, SubjectWrongActivity.class);
            startActivity(intent);
            finish();
        });
    }

    public void setCurrentIndexTitle(int index, int count) {
        String ss = Phrase.from("({index}/{count})").put("index", index).put("count", count).format().toString();
        setTitle(title + ss);
    }


    //设置切换的时间
    public void setSliderTransformDuration(ViewPager viewPager, int duration) {
        try {
            Field mScroller = ViewPager.class.getDeclaredField("mScroller");
            mScroller.setAccessible(true);
            FixedSpeedScroller scroller = new FixedSpeedScroller(viewPager.getContext(), null, duration);
            mScroller.set(viewPager, scroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onCollectSuccess(int resourceId, boolean status) {
        refreshMenuView();
    }


    public class FixedSpeedScroller extends Scroller {

        private int mDuration = 1000;

        public FixedSpeedScroller(Context context) {
            super(context);
        }

        public FixedSpeedScroller(Context context, Interpolator interpolator) {
            super(context, interpolator);
        }

        public FixedSpeedScroller(Context context, Interpolator interpolator, int duration) {
            this(context, interpolator);
            mDuration = duration;
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy, int duration) {
            // Ignore received duration, use fixed one instead
            super.startScroll(startX, startY, dx, dy, mDuration);
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy) {
            // Ignore received duration, use fixed one instead
            super.startScroll(startX, startY, dx, dy, mDuration);
        }
    }
}